<template>
  <div class="security-settings">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>安全设置</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordForm"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
            style="max-width: 600px"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input
                v-model="passwordForm.currentPassword"
                type="password"
                placeholder="请输入当前密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updatePassword">确认修改</el-button>
              <el-button @click="resetForm('passwordForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="手机绑定" name="phone">
          <el-form
            ref="phoneForm"
            :model="phoneForm"
            :rules="phoneRules"
            label-width="120px"
            style="max-width: 600px"
          >
            <el-form-item label="当前手机">
              <div class="bind-status">
                <span>{{ userPhone || '未绑定' }}</span>
                <el-tag v-if="userPhone" type="success" size="small">已绑定</el-tag>
                <el-tag v-else type="info" size="small">未绑定</el-tag>
              </div>
            </el-form-item>
            
            <template v-if="phoneChangeMode">
              <el-form-item label="新手机号" prop="newPhone">
                <el-input
                  v-model="phoneForm.newPhone"
                  placeholder="请输入新手机号"
                />
              </el-form-item>
              
              <el-form-item label="验证码" prop="verifyCode">
                <div class="verify-code-container">
                  <el-input
                    v-model="phoneForm.verifyCode"
                    placeholder="请输入验证码"
                  />
                  <el-button
                    type="primary"
                    :disabled="codeButtonDisabled"
                    @click="sendVerifyCode"
                  >
                    {{ codeButtonText }}
                  </el-button>
                </div>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="updatePhone">确认修改</el-button>
                <el-button @click="phoneChangeMode = false">取消</el-button>
              </el-form-item>
            </template>
            
            <el-form-item v-else>
              <el-button type="primary" @click="phoneChangeMode = true">
                {{ userPhone ? '修改手机号' : '绑定手机号' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="登录安全" name="loginSecurity">
          <div class="security-option">
            <div class="security-option-info">
              <h4>双因素认证</h4>
              <p>开启后，登录时除了输入密码，还需要输入额外的验证码</p>
            </div>
            <el-switch
              v-model="securityOptions.twoFactorAuth"
              @change="updateSecurityOption('twoFactorAuth')"
            />
          </div>
          
          <div class="security-option">
            <div class="security-option-info">
              <h4>登录通知</h4>
              <p>开启后，每次登录系统都会收到邮件通知</p>
            </div>
            <el-switch
              v-model="securityOptions.loginNotification"
              @change="updateSecurityOption('loginNotification')"
            />
          </div>
          
          <div class="security-option">
            <div class="security-option-info">
              <h4>异地登录验证</h4>
              <p>开启后，检测到异地登录时将进行额外验证</p>
            </div>
            <el-switch
              v-model="securityOptions.locationVerify"
              @change="updateSecurityOption('locationVerify')"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'SecuritySettings',
  setup() {
    const activeTab = ref('password')
    const passwordFormRef = ref(null)
    const phoneFormRef = ref(null)
    
    // 密码修改表单
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value.length < 6) {
          callback(new Error('密码长度不能小于6位'))
        } else if (!/\d/.test(value) || !/[a-zA-Z]/.test(value)) {
          callback(new Error('密码必须包含数字和字母'))
        } else {
          if (passwordForm.confirmPassword !== '') {
            passwordFormRef.value.validateField('confirmPassword')
          }
          callback()
        }
      }
    }
    
    const validateConfirmPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, trigger: 'blur', validator: validatePass }
      ],
      confirmPassword: [
        { required: true, trigger: 'blur', validator: validateConfirmPass }
      ]
    }
    
    // 手机绑定表单
    const phoneChangeMode = ref(false)
    const userPhone = ref('13800138000') // 从用户信息中获取
    
    const phoneForm = reactive({
      newPhone: '',
      verifyCode: ''
    })
    
    const phoneRules = {
      newPhone: [
        { required: true, message: '请输入新手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      verifyCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为6位', trigger: 'blur' }
      ]
    }
    
    const codeButtonText = ref('获取验证码')
    const codeButtonDisabled = ref(false)
    let countdownTimer = null
    
    // 安全选项
    const securityOptions = reactive({
      twoFactorAuth: false,
      loginNotification: true,
      locationVerify: true
    })
    
    // 获取安全设置信息
    const fetchSecuritySettings = () => {
      // TODO: 这里需要调用实际API获取安全设置信息
    }
    
    // 修改密码
    const updatePassword = () => {
      passwordFormRef.value.validate((valid) => {
        if (valid) {
          // TODO: 这里需要调用实际API提交修改密码请求
          ElMessage.success('密码修改成功，下次登录请使用新密码')
          resetForm('passwordForm')
        } else {
          return false
        }
      })
    }
    
    // 重置表单
    const resetForm = (formName) => {
      if (formName === 'passwordForm') {
        Object.keys(passwordForm).forEach(key => {
          passwordForm[key] = ''
        })
      } else if (formName === 'phoneForm') {
        Object.keys(phoneForm).forEach(key => {
          phoneForm[key] = ''
        })
      }
    }
    
    // 发送验证码
    const sendVerifyCode = () => {
      phoneFormRef.value.validateField('newPhone', (valid) => {
        if (!valid) {
          // 验证手机号码
          // 这里应该调用API发送验证码
          codeButtonDisabled.value = true
          let countdown = 60
          codeButtonText.value = `${countdown}秒后重新获取`
          
          countdownTimer = setInterval(() => {
            countdown--
            codeButtonText.value = `${countdown}秒后重新获取`
            if (countdown <= 0) {
              clearInterval(countdownTimer)
              codeButtonDisabled.value = false
              codeButtonText.value = '获取验证码'
            }
          }, 1000)
          
          ElMessage.success('验证码已发送，请注意查收')
        }
      })
    }
    
    // 更新手机号
    const updatePhone = () => {
      phoneFormRef.value.validate((valid) => {
        if (valid) {
          // TODO: 这里需要调用实际API提交修改手机号请求
          userPhone.value = phoneForm.newPhone
          phoneChangeMode.value = false
          resetForm('phoneForm')
          ElMessage.success('手机号码更新成功')
        } else {
          return false
        }
      })
    }
    
    // 更新安全选项
    const updateSecurityOption = (option) => {
      // TODO: 这里需要调用实际API更新安全设置
      ElMessage.success(`${option === 'twoFactorAuth' ? '双因素认证' : option === 'loginNotification' ? '登录通知' : '异地登录验证'}设置已更新`)
    }
    
    onMounted(() => {
      fetchSecuritySettings()
    })
    
    return {
      activeTab,
      passwordFormRef,
      phoneFormRef,
      passwordForm,
      passwordRules,
      phoneForm,
      phoneRules,
      userPhone,
      phoneChangeMode,
      codeButtonText,
      codeButtonDisabled,
      securityOptions,
      updatePassword,
      resetForm,
      sendVerifyCode,
      updatePhone,
      updateSecurityOption
    }
  }
}
</script>

<style scoped>
.security-settings {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.verify-code-container {
  display: flex;
  gap: 10px;
}

.verify-code-container .el-button {
  min-width: 120px;
}

.bind-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.security-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #EBEEF5;
}

.security-option:last-child {
  border-bottom: none;
}

.security-option-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.security-option-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}
</style> 